package app.util.image.action
{
	import app.util.*;
	import app.util.image.calc.*;
	
	import flash.display.*;
	import flash.filters.*;
	import flash.geom.*;
	
	import mx.collections.*;
	
	public class MedianAction extends TimeConsumingAction
	{	
		private var size:int;
		private var ret:BitmapData;
		private var old:BitmapData;
		private	var w:int;
		private	var h:int;			
		private var half:int;
		private var currentY:int;
		
		private var neighbors:ArrayCollection = new ArrayCollection();
			
		public function MedianAction(size:int)
		{
			this.size = size;	
			this.half = this.size >> 1;
		}
		
		public override function getDescription():String
		{
			return "Median Filter " + this.size + "x" + this.size;
		}
		
		protected override function getFinalBitmapData():BitmapData
		{
			return this.ret;
		}
		
		protected override function processBitmapDataByStep():Number
		{
			if(this.ret == null)
			{
				this.old = Mediator.getCurrentBitmapData();
				this.w = this.old.width;
				this.h = this.old.height;
				this.currentY = 0;
				this.ret = new BitmapData(w, h);			
			}
			
			for(var i:int = 0; i < this.w; i++)
			{
				neighbors.removeAll();
				for(var x:int = i - half; x < i + half; x++)
				{
					for(var y:int = this.currentY - half; y < this.currentY + half; y++)
					{
						neighbors.addItem(this.old.getPixel(x, y));
					}
				}
				ret.setPixel(i, this.currentY, MathUtility.calcMedian(neighbors.toArray()));
			}
			
			return (++this.currentY) / this.h;			
		}
	}
}